package com.lsj.fileutil;

import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
@Component
public class FileUtil {
    /**
     * txt文件 按行读取
     * @param filePath
     * @return
     */
    public List<String> read(String filePath) throws Exception {
        List<String> list = new ArrayList<String>();
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null; //用于包装InputStreamReader,提高处理性能。因为BufferedReader有缓冲的，而InputStreamReader没有。
        try {
            String str = null;
            fis = new FileInputStream(filePath);// FileInputStream
            // 从文件系统中的某个文件中获取字节
            isr = new InputStreamReader(fis,"utf-8");// InputStreamReader 是字节流通向字符流的桥梁,
            br = new BufferedReader(isr);// 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
            while ((str = br.readLine()) != null) {
                list.add(str);
                System.out.println(str+";");// 打印出str
            }
        } catch (FileNotFoundException e) {
            System.out.println("找不到指定文件");
            throw new Exception("找不到指定文件");
        } catch (IOException e) {
            System.out.println("读取文件失败");
            throw new Exception("读取文件失败");
        } finally {
            try {
                br.close();
                isr.close();
                fis.close();
                // 关闭的时候最好按照先后顺序关闭最后开的先关闭所以先关s,再关n,最后关m
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    //txt文件写入信息
    public void write(String fileurl, List<String> lstrList){
        try {
            File file = new File(fileurl);
            creatFile(file);
            BufferedWriter output = new BufferedWriter(new FileWriter(file));
            //写入文件()
            for(String str:lstrList){
                output.write(str.toString());
                output.newLine();
            }
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void creatFile(File target){
        try{
            File fileParent = target.getParentFile();
            if(!fileParent.exists()){
                fileParent.mkdirs();
            }
            target.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



}
